package com.itheima.controller;

import com.alibaba.dubbo.config.annotation.Reference;
import com.itheima.constant.MessageConstant;
import com.itheima.entity.PageResult;
import com.itheima.entity.QueryPageBean;
import com.itheima.entity.Result;
import com.itheima.pojo.Menu;
import com.itheima.service.MenuService;
import org.springframework.web.bind.annotation.*;

import java.util.List;

@RestController
@RequestMapping("/menu")
public class MenuController {

    @Reference
    private MenuService menuService;

    /**
     * 1.分页+模糊查询
     *
     * @return
     */
    @PostMapping("/pagination")
    public PageResult pagination(@RequestBody QueryPageBean pageBean) {
        try {
            return menuService.queryPage(pageBean);
        } catch (Exception e) {
            e.printStackTrace();
            return null;
        }
    }

    /**
     * 2.查询所有的父级菜单id
     *
     * @return
     */
    @GetMapping("/preCreate")
    public Result preCreate() {
        List<Menu> list = null;
        try {
            list = menuService.getParentMenuIds();
        } catch (Exception e) {
            e.printStackTrace();
            return new Result(false, MessageConstant.GET_MENU_ID_LIST_FAIL);
        }
        return new Result(true, MessageConstant.GET_MENU_ID_LIST_SUCCESS, list);
    }

    /**
     * 3.创建菜单
     *
     * @param menu
     * @return
     */
    @PostMapping("/create")
    public Result create(@RequestBody Menu menu) {
        try {
            menuService.addMenu(menu);
            return new Result(true, MessageConstant.ADD_MENU_SUCCESS);
        } catch (Exception e) {
            return new Result(true, MessageConstant.ADD_MENU_FAIL);
        }
    }

    /**
     * 4.获取菜单数据
     *
     * @param id
     * @return
     */
    @GetMapping("/preUpdate/{id}")
    public Result preUpdate(@PathVariable Integer id) {
        try {
            Menu menu = menuService.getMenuById(id);
            return new Result(true, MessageConstant.GET_MENU_INFO_SUCCESS, menu);
        } catch (Exception e) {
            e.printStackTrace();
            return new Result(false, MessageConstant.GET_MENU_INFO_FAIL);
        }
    }


    /**
     * 5.更新菜单数据
     *
     * @param menu
     * @return
     */
    @PostMapping("/update")
    public Result update(@RequestBody Menu menu) {
        try {
            menuService.updateMenu(menu);
            return new Result(true, MessageConstant.EDIT_MENU_SUCCESS);
        } catch (Exception e) {
            e.printStackTrace();
            return new Result(false, MessageConstant.EDIT_MENU_FAIL);
        }
    }

    @DeleteMapping("/delete/{id}")
    public Result delete(@PathVariable Integer id) {
        try {
            return menuService.deleteMenuById(id);
        } catch (Exception e) {
            e.printStackTrace();
            return null;
        }
    }
}
